package com.gxa.feedback.controller;

import com.gxa.common.R;

import com.gxa.common.utils.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Controller
@ResponseBody
public class UploadController {

    @Value("${filePath}")
    private String filePath;
    @Value("${imageUrl}")
    private String imageUrl;

    //配置限制运行文件上传的格式
    private static  final List<String> extList= Arrays.asList(".jpg",".png",".bmp",".pdf",".txt",".md",".sql",".xlsx",".docx");

    private Logger log = LoggerFactory.getLogger(UploadController.class);


    @PostMapping(value ="/uploadImage")
    public R upload(@RequestParam MultipartFile image) throws IOException {
        System.out.println("文件路径"+filePath);
        System.out.println("ip地址"+imageUrl);
        //获取上传的图片
        //Part封装了上传文件的相关信息
        //通过上传的字段名获取图片
        String filename = image.getOriginalFilename();
        log.debug("上传文件的名字为:{}",filename);

        //获取文件的后缀
        String ext = filename.substring(filename.lastIndexOf("."));

        log.debug("上传文件的扩展名为:{}",ext);

        if(!extList.contains(ext)){
            //格式不合法
            log.error("格式不合法名为:{}",ext);
            return ResultUtils.buildFail(500,"上传失败");
        }
        //生成新的文件名
        String newFileName = UUID.randomUUID().toString().replace("-","")+ext;

        log.info("新生成的文件名:{}",newFileName);

        log.debug("上传文件的路径:{}",filePath);
        //处理图片上传
        image.transferTo(new File(filePath+File.separator+newFileName));

        log.debug("图片的访问路径:{}",imageUrl + newFileName);
        return  ResultUtils.buildSuccess(imageUrl + newFileName);
    }
}
